const TOKEN_KEY = 'token'
const ROLE_KEY = 'role'
const USER_KEY = 'user'

// 在关闭浏览器后会自动清除
const storage = sessionStorage
// 获取token
export const getToken = () => {
  return storage.getItem(TOKEN_KEY)
}

// 设置token
export const setToken = (token) => {
  if (!token || typeof token !== 'string') {
    throw new Error('Invalid token')
  }
  return storage.setItem(TOKEN_KEY, token)
}

// 移除token
export const removeToken = () => {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(ROLE_KEY)
  localStorage.removeItem(USER_KEY)
  storage.clear() // 清除所有数据
}

// 获取用户角色
export const getRole = () => {
  return localStorage.getItem(ROLE_KEY)
}

// 设置用户角色
export const setRole = (role) => {
  if (!role || typeof role !== 'string') {
    throw new Error('Invalid role')
  }
  return storage.setItem(ROLE_KEY, role)
}

// 获取用户信息
export const getUser = () => {
  try {
    const userStr = storage.getItem(USER_KEY)
    return userStr ? JSON.parse(userStr) : null
  } catch (error) {
    console.error('解析用户信息失败:', error)
    return null
  }
}

// 设置用户信息
export const setUser = (user) => {
  try {
    if (!user || typeof user !== 'object') {
      throw new Error('Invalid user data')
    }
    storage.setItem(USER_KEY, JSON.stringify(user))
  } catch (error) {
    console.error('保存用户信息失败:', error)
    throw error
  }
}

// 检查是否已登录
export const isAuthenticated = () => {
   return storage.getItem('isAuthenticated') === 'true'
}

// 保存登录信息
export const saveLoginInfo = (data) => {
  try{
    removeToken() // 先清除旧数据
  if (data.token) setToken(data.token)
  if (data.role) setRole(data.role)
  if (data.user) setUser(data.user)
  storage.setItem('isAuthenticated', 'true') // 添加登录状态标记
}catch (error) {
    console.error('保存登录信息失败:', error)
    throw error
  }
}
